<!-- filepath: frontend/src/components/Login.vue -->
<template>
  <div class="login-form-container">
    <h2>登录</h2>
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" status-icon @submit.prevent="handleLogin">
      <el-form-item prop="username">
        <!-- 确保有 placeholder -->
        <el-input
          v-model="loginForm.username"
          placeholder="用户名"
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <!-- 确保有 placeholder -->
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="密码"
          show-password
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
      </el-form-item>
    </el-form>
    <div class="switch-auth-mode">
      还没有账户？ <span @click="$emit('switch-to-register')">立即注册</span>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuth } from '../composables/useAuth';
import { User, Lock } from '@element-plus/icons-vue';

const emit = defineEmits(['login-success', 'switch-to-register']);

const loginForm = ref({
  username: '',
  password: '',
});

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const loading = ref(false);

const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码');
    return;
  }
  loading.value = true;
  try {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: loginForm.value.username,
        password: loginForm.value.password,
      }),
    });

    const data = await response.json();
    
    if (response.ok) {
      const token = data.access_token;
      if (!token || typeof token !== 'string') {
        console.error('Invalid token received:', token);
        ElMessage.error('服务器返回了无效的认证令牌');
        return;
      }
      
      console.log("Login.vue: Emitting login-success event with data:", { token, user: data.user });
      emit('login-success', { token, user: data.user });
    } else {
      ElMessage.error(data.error || '登录失败');
    }
  } catch (error) {
    console.error('Login error:', error);
    ElMessage.error('登录过程中发生错误');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 移除所有样式规则，因为它们现在由 LoginPage.vue 控制 */
.login-form-container {
  width: 100%; /* 确保填满父容器 */
}
</style>

